package club.dmyang.service;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.exception.HyBlogException;
import club.dmyang.dao.CommentMapper;
import club.dmyang.entity.Comment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by brss on 2018/7/24.
 */
@Service("commentServiceImpl")
public class CommentServiceImpl implements CommentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommentServiceImpl.class);

    @Autowired
    private CommentMapper commentMapper;

    /**
     * 分页的前提下
     * 根据文章Id查询评论
     *
     * @param aid
     * @param page
     * @param limit @return
     */
    @Override
    public List<Comment> selectByArticleId(Integer aid, Integer page, Integer limit) {
        if ( page < 1 || limit < 1 ){
            LOGGER.error("page或limit错误！[ page = "+page + "limit = "+limit + "]");
            throw new HyBlogException(RespCodeEnums.GLOBAL_CODE_PARAMETER_ERROR);
        }
        return commentMapper.selectByArticleId(aid,(page-1)*limit,limit);
    }

    /**
     * 查询一个文章id下一共有多少条评论
     * （用于计算分页总页数）
     *
     * @param aid
     * @return
     */
    @Override
    public int selectNumsByArticleId(Integer aid) {
        return commentMapper.selectNumsByArticleId(aid);
    }

    /**
     * 添加一条评论
     *
     * @param comment
     */
    @Override
    public Comment addOneComment(Comment comment) {
        try {
            //插入时，主键被返回
            commentMapper.insert(comment);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加评论失败,内容为："+comment.getContent());
            return null;
        }
        return comment;
    }

    /**
     * 对评论点赞
     * 防恶意点赞
     *
     * @param commentId
     * @return
     */
    @Override
    public int voteOneComment(Integer commentId) {
        //查出找条评论
        Comment dbComment = commentMapper.selectByPrimaryKey(commentId);
        if (dbComment != null){
            dbComment.setVotes(dbComment.getVotes()+1);
            return commentMapper.updateByPrimaryKey(dbComment);
        }
        return 0;
    }
}
